//
// Created by hkkzzxz on 24-8-31.
//

#include "UnderlyingServer.h"

void UnderlyingServer::start(int &serverPort) {
    auto const address = net::ip::make_address("0.0.0.0");
    auto port = static_cast<unsigned short>(serverPort);
    
    int numThreads = std::thread::hardware_concurrency() * 2 + 2;
    net::io_context ioc{numThreads};

    tcp::acceptor acceptor{ioc, {address, port}};
    tcp::socket socket{ioc};
    httpServer(acceptor, socket);

    consoleLogger->info("UnderlyingServer start on port:" + std::to_string(port));

    ioc.run();
}

void UnderlyingServer::httpServer(tcp::acceptor &acceptor, tcp::socket &socket) {
    acceptor.async_accept(socket, [&](beast::error_code ec) {
        if (!ec) {
            std::make_shared<HttpConnection>(std::move(socket))->start();
        }
        httpServer(acceptor, socket);
    });
}
